//The MIT License
//
//Copyright (c) 2009 nodchip
//
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in
//all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//THE SOFTWARE.
package tv.dyndns.kishibe.client;

import tv.dyndns.kishibe.client.packet.PacketProblemData;
import tv.dyndns.kishibe.client.packet.PacketResult;
import tv.dyndns.kishibe.client.statistics.PanelStatisticsRatingHistory;
import tv.dyndns.kishibe.client.statistics.PanelStatisticsUserAccuracyRate;
import tv.dyndns.kishibe.client.util.SerialTimer;

import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.rpc.AsyncCallback;

public class SceneResult implements SceneBase {
	private final PanelResult panel;

	public SceneResult(PacketProblemData[] problems) {
		panel = new PanelResult(problems);
		Controller.getInstance().setGamePanel(panel);
	}

	private final Timer timerGetResult = new SerialTimer() {
		public void run() {
			getResult();
		}
	};

	private void getResult() {
		final int sessionId = SharedData.getInstance().getSessionId();
		Service.Util.getInstance().getResult(sessionId, callbackGetResult);
	}

	private final AsyncCallback<PacketResult[]> callbackGetResult = new AsyncCallback<PacketResult[]>() {
		public void onSuccess(PacketResult[] result) {
			if (result == null) {
				timerGetResult.schedule(1000);
				Controller.getInstance().showErrorMessage("SceneResult.getResult() - 無効な最終結果が返されました。パケットを再送します。");
				return;
			}

			panel.setPlayerList(result);

			PacketResult playerResult = null;
			for (int i = 0; i < result.length && playerResult == null; ++i) {
				if (result[i].playerListId == SharedData.getInstance().getPlayerListIndex()) {
					playerResult = result[i];
				}
			}

			// プレイヤー履歴書き換え
			final UserData record = UserData.getInstance();

			// ハイスコア更新
			if (!SharedData.getInstance().isThemeMode() && record.getHighScore() < playerResult.score) {
				record.setHighScore(playerResult.score);
			}

			// プレイ回数
			int playCount = record.getPlayCount();
			if (playCount == Integer.MAX_VALUE) {
				playCount = 0;
			}
			++playCount;
			record.setPlayCount(playCount);

			// 平均得点
			if (!SharedData.getInstance().isThemeMode()) {
				int averageScore = record.getAverageScore() * (record.getPlayCount() - 1);
				averageScore += playerResult.score;
				averageScore /= record.getPlayCount();
				record.setAverageScore(averageScore);
			}

			// 平均順位
			float avarageRank = record.getAverageRank() * (float) (record.getPlayCount() - 1);
			avarageRank += (float) playerResult.rank;
			avarageRank /= record.getPlayCount();
			record.setAvarageRank(avarageRank);

			// レーティング計算
			int rating = record.getRating();
			rating += playerResult.ratingDelta;
			record.setRating(rating);
			Service.Util.getInstance().addRatingHistory(UserData.getInstance().getUserCode(), rating, Service.NULL_CALLBACK);
			PanelStatisticsRatingHistory.getInstance().resetFlag();

			// クラス
			int classLevel = record.getClassLevel();
			if (playerResult.score >= classLevel * 100 + 500 || playerResult.rank == 1) {
				if (++classLevel >= (Constant.MAX_CLASS_LEVEL + 1) * Constant.STEP_PER_CLASS_LEVEL) {
					classLevel = (Constant.MAX_CLASS_LEVEL + 1) * Constant.STEP_PER_CLASS_LEVEL - 1;
				}
			} else if (playerResult.score < classLevel * 100 - 500 || playerResult.rank == 8) {
				if (--classLevel <= 0) {
					classLevel = 0;
				}
			}
			record.setClassLevel(classLevel);

			record.save();

			if (PanelStatisticsUserAccuracyRate.getInstance() != null) {
				PanelStatisticsUserAccuracyRate.getInstance().update();
			}
		}

		public void onFailure(Throwable caught) {
			timerGetResult.schedule(Constant.RETRY_DELAY);
			Controller.getInstance().showErrorMessage("SceneResult.SceneResult() - 最終結果の取得に失敗しました。パケットを再送します。");
		}
	};

	public void onLoad() {
		timerGetResult.schedule(1000);
	}

	public void onUnload() {
		timerGetResult.cancel();
	}
}
